<?php

namespace think\wework\Command;


use think\console\Input;
use think\console\Command;
use think\console\input\Argument;
use IO\Github\Wechaty\Wechaty;
use IO\Github\Wechaty\User\Message;
use IO\Github\Wechaty\User\ContactSelf;
use IO\Github\Wechaty\Util\QrcodeUtils;
use Symfony\Component\Process\Process;
use Symfony\Component\Process\PhpExecutableFinder;
use think\console\input\Option;
use think\console\Output;
use think\facade\Cache;
use think\facade\Log;
use think\Wework;

class BotWorker extends Command
{
    protected function configure()
    {
        $this->setName('webot:worker')
            ->addArgument('token', Argument::REQUIRED, '启动一个机器人')
            ->setDescription("启动一个机器人");
    }

    protected function execute(Input $input, Output $output)
    {
        $puppetToken = $input->getArgument('token');
        $redis = Cache::store('redis')->handler();
        $output->token = $puppetToken;
        try {
            // 指令输出
            putenv("WECHATY_PUPPET_SERVICE_NO_TLS_INSECURE_CLIENT=true");
            $bot = Wechaty::getInstance($puppetToken);

            $bot->onScan(function ($qrcode, $status, $data) use ($output, $redis){

//                $output->writeln(var_export($status,true));
//                $qr = QrcodeUtils::getQr($qrcode);

                $message = json_encode(['event'=>'scan', 'status'=>$status,'data'=>'https://www.baidu.com']);
                $redis->hSet(Wework::BotTokenListHash, strtoupper(md5($output->token)), $message);
                Log::bot("[$output->token][onScan]: $qrcode");
//                $output->writeln("QR:\n$qr\nOnline:\nhttps://wechaty.js.org/qrcode/$qrcode");
            });
            $bot->onLogin(function (ContactSelf $user) use ($output) {
                Log::bot("[$output->token][onLogin]: {$user->name()}");
//                $output->writeln("{$user->name()}已登录");
            });
            $bot->onMessage(function (Message $message) use ($output) {
                Log::bot("[$output->token][onMessage]: {$message->talker()->name()}：{$message->text()}");
//                $output->writeln("{$message->talker()->name()}：{$message->text()}");
            });
            $bot->start();
        } catch (\Exception $e) {
            Log::bot("[$output->token][Exception]: {$e->getMessage()} in {$e->getFile()}:{$e->getLine()}");
//            $output->writeln("Exception：{$e->getMessage()}");
        }
    }
}